import Vue from "vue";
import Vuex from "vuex";
import json from '@/common/json.js';

Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		// 画布数据
		mould: null,
		// 画布状态
		mouldStates: false,
		// 画布上的组件集合
		componentList: [],
		// 组件创建的当前序列号
		componentIndex: 0,
		// 选中组件的id
		selectedIndex: null
	},
	getters: {
		mould: state => state.mould,
		mouldStates: state => state.mouldStates,
		componentList: state => state.componentList,
		componentIndex: state => state.componentIndex,
		selectedIndex: state => state.selectedIndex
	},
	mutations: {
		// 创建模板
		createMould(state, val) {
			state.mould = val
			setTimeout(() => {
				state.mouldStates = true
			}, 1000);
		},
		// 删除模板
		deleteMould(state) {
			state.mould = null
			state.componentList = []
			state.componentIndex = 0
			state.selectedIndex = null
			state.mouldStates = false
		},
		// 导出模板
		exportMould() {

		},
		// 导入模板
		importMould() {

		},
		// 创建组件
		createComponentList(state, val) {
			var componentIndex = state.componentIndex,
				cpt = json.components.find(e => {
					return e.type == val.type
				});
			val = Object.assign({
				id: val.type + componentIndex
			}, val, cpt ? cpt.option : {})
			state.componentList.push(val)
			state.componentIndex = componentIndex + 1
		},
		// 选中组件
		selectComponent(state, index) {
			state.selectedIndex = (index == 0 || index > 0) ? index : null
		},
		// 设置组件属性
		setComponentList(state, {
			id,
			data
		}) {
			state.componentList[id] = Object.assign(state.componentList[id], data)
		},
		// 删除组件
		deleteComponentList(state) {
			if (state.selectedIndex > 0 || state.selectedIndex == 0) {
				state.componentList.splice(state.selectedIndex, 1)
				state.selectedIndex = null
			}
		}
	}
});
